# -*- coding: utf-8 -*-
#!/usr/bin/env python

from app import app
from flask import render_template
from flask import request
from flask import redirect
from flask import jsonify
from flask import Flask, render_template, session, redirect, url_for

import MySQLdb 
import MySQLdb.cursors

# 连接数据库 
def connectdb(): 
       db = MySQLdb.connect(host="39.108.8.103", user="root", passwd="admin", db="tradedb", port=3306) 
       db.autocommit(True) 
       cursor = db.cursor() 
       return db,cursor

# 关闭数据库 
def closedb(db,cursor): 
       db.close() 
       cursor.close()

def getdata(count = 10):
	db,cur = connectdb();

	#获取数据
	cur.execute("SELECT * FROM witoil ORDER BY id DESC LIMIT " + str(count))
	a=cur.fetchall()
	name=['code','datetime','price','id']
	datas=[dict(zip(name,x)) for x in a]
	closedb(db,cur)
	return datas

@app.route('/')
def index():
    return render_template("welcome.html",tile="Welcome")


@app.route('/home')
def home():
    return render_template('base.html', title="Home")


@app.route('/post', methods=['POST'])
def home1():
	#获取post来的数据，放在一个字典data里面
	data = json.loads(request.form.get('data'))

	#发送出去数据
	info = dict()
	info['name'] = {"id":12}
	info['lesson'] = [{"id":12},{"id":545}]
	info['score'] = "12asdf"
	return jsonify(data)

@app.route('/getdata',methods=['GET'])
def hello():
	count = request.args.get('count')
	data = getdata(count)
	datas = {"datas":data}
	return jsonify(datas)
